import { Vec2 } from 'cc';
import { find, Sprite, SpriteFrame,tween,Tween,UIOpacity,Game,game as gameCCD, _decorator, Component, Label, Node ,Vec3 } from 'cc'
import { App } from '../../../App';
import AbstractComponent from '../../../base/AbstractComponent';
import { EventConst } from '../../../common/Common';
import CommConst from '../../../const/CommConst';
import wsTool from '../../../net/ws';
import { LoadMg } from '../../../tools/LoadMg';
import { showGameActionPoint, showLuckyBallRule, showTip, showTipBox } from '../../../tools/PopuUp';
import UtilTool from '../../../tools/UtilTool';
import { GameBaseModel } from '../GameBaseModel';
import { ACTION_POINT_R } from '../GameManage';
import { GameModel } from '../model/GameModel';
import { GameModel1 } from './GameModel1';
const { ccclass, property } = _decorator;

// 游戏2D界面
@ccclass('GameLayer1')
export class GameLayer1 extends Component {
    @property(Node)
    bg : Node = null

    @property(Label)
    timeLabel : Label = null

    @property(SpriteFrame)
    ballArr = []

    @property(SpriteFrame)
    barArr = []

    @property(Node)
    roleNodeSpr = []

    public gameMode:GameModel = null
    private timeEnd = false // 倒计时是否结束
    public baseCoin = 0    // 获得基础金币数
    private isBackGround = false
    
    private isTest = false

    // 游戏状态数据
    private gameData = {
        status: 2,      // 当前游戏状态 0下单中 1倒计时 2击球中
        countdown: 10000,   // 倒计时：秒
        period: "0",    // 期数
        nums: 10,        // 本期数字（只有在击球阶段才会有）
        baseOdds: 0,    // 基础赔率
        hitOdds: 0,     // 击中赔率
        isReconnect: 0, // 是否重连 0否 1是
        list: [],       // 订单列表 list[{id=0, nums=0, value=0}]
    }

    onLoad() {
        gameCCD.on(Game.EVENT_HIDE, function(){
            if (this.node==null) return
            if(!this.isBackGround){
                this.isBackGround = true;
                UtilTool.printLog("切换后台");
                
            }
        }.bind(this));
        gameCCD.on(Game.EVENT_SHOW, function(){
            if (this.node==null) return
            if(this.isBackGround){
                UtilTool.printLog("切换前台");    
                this.isBackGround = false;
                this.reqGameData()
            }
        }.bind(this));
    }

    start() {
        this.gameMode = App.Model.gameModel

        this.reqGameData(true)  

        // 关闭球洞
        find("holeNode",this.node).active = false
        setTimeout(() => {
            // 获取球洞列表
            let gameView = App.Model.gameView as GameModel1
            let roleNodeList = gameView.roleNodeList
            for (let i = 0; i < roleNodeList.length; i++) {
                let item = roleNodeList[i]
                if (item) {
                    let localPos = gameView.World3DToLocal(item.worldPosition)
                    if (this.roleNodeSpr[i]) {
                        this.roleNodeSpr[i].setPosition(localPos.x, localPos.y)
                    }
                }
            }

            gameView.setHoleSwitch(false)
        }, 100)

        this.setActionPoint(new Vec2(0,0))
        //更新作用点位置
        App.Event.on(EventConst.ACTION_BALL_POINT,(data)=>{
            this.setActionPoint(data)
        },this)
    }

    update(deltaTime: number) {
        
    }

    // 请求游戏数据
    reqGameData(init) {
        if (this.timeEnd) {
            return
        }

        let that = this
        if (this.isTest) {
            that.gameMode.model1_data = this.gameData
            find("ballSpr",that.bg).getComponent(Sprite).spriteFrame = that.ballArr[that.gameData.nums]
            find("energyLabel",that.bg).getComponent(Label).string = App.language.getLanguageLab(36) + that.gameData.nums
            find("ratioLabel",that.bg).getComponent(Label).string = "x" + that.gameData.hitOdds
            find("coinbg/coinLabel",that.bg).getComponent(Label).string = "" + that.getBaseAward()

            // 设置能力力度显示
            that.setEnergy(that.gameData.nums)

            that.setTimeAction(init)

            if (init) {
                let gameView = App.Model.gameView as GameModel1
                showTip(App.language.getLanguageLab(48))
                gameView.goSystemPlayball()
            }

            return
        }

        wsTool.send({"msgCode":CommConst.Req_ENTERGAME,"noLoad":false})
        .then(res =>{
            // if (res?.result == 0) {
                UtilTool.printLog("游戏数据:",res)
                that.gameMode.model1_data = res
                that.setGameConfig(res)
                if (that.gameData.status==2 && that.isLottery(that.gameData.nums)) {
                    // 设置数据
                    find("ballSpr",that.bg).getComponent(Sprite).spriteFrame = that.ballArr[that.gameData.nums]
                    find("energyLabel",that.bg).getComponent(Label).string = App.language.getLanguageLab(36) + that.gameData.nums
                    find("ratioLabel",that.bg).getComponent(Label).string = "x" + that.gameData.hitOdds
                    find("coinbg/coinLabel",that.bg).getComponent(Label).string = "" + that.getBaseAward()

                    // 设置能力力度显示
                    that.setEnergy(that.gameData.nums)

                    that.setTimeAction(init)

                    if (init) {
                        let gameView = App.Model.gameView as GameModel1
                        showTip(App.language.getLanguageLab(48))
                        gameView.goSystemPlayball()
                    }
                }
                else {
                    UtilTool.printLog("非击球阶段:", that.gameData.status, that.isLottery(that.gameData.nums))
                    App.Model.gameView.backToHall()
                }

            // }
            // else{
            //     alert('获取数据失败')
            // }
        })
    }

    /**
     * 设置倒计时动画
     */
    setTimeAction(init=false) {
        let that = this

        let ratioLabel = find("ratioLabel",this.bg)
        UtilTool.timeCountdown(this.timeLabel, null, this.gameData.countdown, ()=>{
            App.Model.gameModel.model1Status = App.Model.gameModel.MODEL1_STATUS.STATUS_FAIL
            showTipBox({
                content:App.language.getLanguageLab(47),
                func:()=>{
                    App.Model.gameView.backToHall()
                }
              })

            that.timeEnd = true
        })
        
        if (init) {
            tween(ratioLabel)
            .to(0.5,{scale: new Vec3(1.4, 1.4, 1.0)})
            .to(0.5,{scale: new Vec3(1.0, 1.0, 1.0)})
            .delay(0.5)
            .call(() => {
                that.timeLabel.node.getComponent(UIOpacity).opacity = 255
                ratioLabel.active = false
            })
            .start()
        }
        
    }

    /**
     * 停止倒计时
     */
    stopDJS() {
        Tween.stopAllByTarget(this.timeLabel.node)
        this.timeEnd = true
    }
    
    /**
     * 设置游戏数据
     */
    setGameConfig(data) {
        if (data==null) return

        this.gameData.status = data.status
        this.gameData.countdown = data.countdown
        this.gameData.period = data.period
        this.gameData.nums = parseInt(data.nums)
        this.gameData.baseOdds = data.baseOdds
        this.gameData.hitOdds = data.hitOdds
        this.gameData.isReconnect = data.isReconnect
        this.gameData.list = data.list
    }

    /**
     * 获取基础奖励值
     */
    getBaseAward() {
        if (this.gameData.status!=2) return

        let value = 0 // 投注的钱
        for (let i = 0; i < this.gameData.list.length; i++) {
            const data = this.gameData.list[i]
            if (parseInt(data.nums) == this.gameData.nums) {
                value = data.value
                break
            }
        }

        this.baseCoin = value*this.gameData.baseOdds
        return this.baseCoin
    }

    /** 
     * 判断是否中奖
      */
    isLottery(number) {
        let lottery = false
        for (let i = 0; i < this.gameData.list.length; i++) {
            const data = this.gameData.list[i]
            if (parseInt(data.nums) == number) {
                lottery = true
                break
            }
        }

        return lottery
    }

    /** 
     * 获取订单号
      */
    getOrderId() {
        let id = 0
        for (let i = 0; i < this.gameData.list.length; i++) {
            const data = this.gameData.list[i]
            if (parseInt(data.nums) == this.gameData.nums) {
                id = data.id
                break
            }
        }

        return id
    }

    /** 
     * 设置开球力度显示
      */
    setEnergy(value) {
        if (value<0 || value>15) {return}

        for (let i = 1; i <= 5; i++) {
            let bar = find("energybg/bar" + i,this.bg).getComponent(Sprite)

            let index = 0
            let level1 = 3*i
            let level2 = 3*(i-1)

            if (value>level1) {
                index = 3
            }else {
                index = (value-level2) % 4
            }

            if (index-1>=0) {
                bar.node.active = true
                bar.spriteFrame = this.barArr[index-1]
            }
            else {
                bar.node.active = false
            }
        }
    }

    /** 
     * 玩法说明
      */
    clickRule() {
        App.Audio.playOneShot("click")
        showLuckyBallRule(this.node)
    }
    
    /** 
     * 关闭
      */
    clickClose() {
        App.Audio.playOneShot("click")

        showTipBox({content:App.language.getLanguageLab(49), btnType:3, func : ()=>{
            // hitStatus 击球结果 1已进洞 2未进洞 
            wsTool.send({"msgCode":CommConst.Req_HITBALL_RESOULT, "hitStatus":2, "id":this.getOrderId()})
            .then(res =>{
                if (res?.result == 0) {
                    UtilTool.printLog("击球结果:",res)
                    App.Model.gameView.backToHall()
                    return
                }
                App.Model.gameView.backToHall()
            })
            
        }})
    }

    protected onDestroy(): void {
        App.Event.off(EventConst.ACTION_BALL_POINT, this.setActionPoint, this)
    }

    /** 
     * 点击作用点
      */
    clickActionPoint() {
        let gameView = App.Model.gameView as GameBaseModel
        showGameActionPoint(gameView.viewNode)
    }

    /** 
     * 设置作用点
      */
    setActionPoint(pos) {
        let ratio = 50 / ACTION_POINT_R
        let point = find("actionBall/redpoint",this.node)
        point.setPosition(pos.x * ratio, pos.y * ratio)

        if (pos.x == 0 && pos.y == 0) {
            App.Model.gameManage.ballActionDial = 0
            App.Model.gameManage.setActionPoint(pos)
            App.Event.emit(EventConst.GAME_HIT_ACTIONVIEW)
        }
    }

}

